<?php



namespace addons\litestore\controller\api;



use app\common\controller\Api;

use addons\litestore\model\Wxlitestoregoods;

use addons\litestore\model\Litestoregoodsspec;

use think\Db;

use fast\Tree;

class Goods extends Api

{

    protected $noNeedLogin = ['*'];



    public function _initialize()

    {

        parent::_initialize();

    }



    public function detail()

    {

        $goods_id = $this->request->request('goods_id');
        $shangjia_id = $this->request->request('shangjia_id');

        // 商品详情

        $detail = Wxlitestoregoods::detail($goods_id);

        $imgs=[];

        foreach (explode(",",$detail['images']) as $index => $item) {

            $imgs[] = cdnurl($item, true);

        }

        $detail['imgs_url'] = $imgs;



        if (!$detail || $detail['goods_status'] !== '10') {

            $this->error('很抱歉，商品信息不存在或已下架');

        }

        // 规格信息

        $specData = $detail['spec_type'] === '20' ? $detail->getManySpecData($detail['spec_rel'], $detail['spec']) : null;
        // 这里对规格的img格式化

        // if($specData!=null){

        //     foreach($specData['spec_list'] as $index => $item){

        //         $specData['spec_list'][$index]["form"]['imgshow'] = $specData['spec_list'][$index]["form"]['spec_image']==='' ? null:cdnurl($specData['spec_list'][$index]["form"]['spec_image'], true);

        //     }

        // }

        $detail = $detail->toArray();
        foreach ($detail['spec'] as $key => $value) {

         

            $spec_sku_id = explode('_',$value['spec_sku_id']);

            $detail['spec'][$key]['goods_sku_id_arr'] = $spec_sku_id;

        }

        foreach ($detail['spec'] as $key => $value) {

            $detail['spec'][$key]['checked'] = false;

            $detail['spec'][$key]['goods_num'] = 0;

        }







        $user_vip = [];



        if($this->auth->id){

            $map2['user_id'] = $this->auth->id;

            $map2['status'] = '1';


            $user_vip = Db::table('fa_pifa_md')->where($map2)->find();

        }

        $baojia_id = 0;
        if ($this->auth->id) {
           $user = Db::table('fa_user')->find($this->auth->id);
           if (!empty($user['baojia_id'])) {
               $baojia_id = $user['baojia_id'];
           }
        }

        if (!empty($user_vip)) {

            foreach ($detail['spec'] as $key => $value) {
                 $price = $value['goods_price2'];
                 if (!empty($baojia_id) && !empty($value['baojia'])) {
                    $baojia = json_decode($value['baojia'],true);
                    if (isset($baojia[$baojia_id])) {
                        $price = bcadd($price, $baojia[$baojia_id],2);
                        if ($price <= 0) {
                            $price = 0.01;
                        }
                       
                    }
                }
                if (!empty($shangjia_id) && !empty($value['baojia_quyu'])) {
                    $baojia_quyu = json_decode($value['baojia_quyu'],true);

                 
                    if (isset($baojia_quyu[$shangjia_id])) {
                        $price = bcadd($price, $baojia_quyu[$shangjia_id],2);

                        if ($price <= 0) {
                            $price = 0.01;
                        }
                    }
                }

                 $detail['spec'][$key]['goods_price'] = $price;
                 $detail['spec'][$key]['goods_price2'] = $price;


            }

            

        }else{
             foreach ($detail['spec'] as $key => $value) {

                $price = $value['goods_price'];

                if (!empty($baojia_id) && !empty($value['baojia'])) {
                    $baojia = json_decode($value['baojia'],true);
                    if (isset($baojia[$baojia_id])) {
                        $price = bcadd($price, $baojia[$baojia_id],2);
                        if ($price <= 0) {
                            $price = 0.01;
                        }
                    }
                }
                
                if (!empty($shangjia_id) && !empty($value['baojia_quyu'])) {
                    $baojia_quyu = json_decode($value['baojia_quyu'],true);

                    if (isset($baojia_quyu[$shangjia_id])) {
                        $price = bcadd($price, $baojia_quyu[$shangjia_id],2);

                        if ($price <= 0) {
                            $price = 0.01;
                        }
                       
                    }
                }
                $detail['spec'][$key]['goods_price'] = $price;  
                $detail['spec'][$key]['goods_price2'] = $price;  

            }

        }



        if (isset($specData['spec_list'])) {
           foreach ($specData['spec_list'] as $key => $value) {
               if (!empty($user_vip)) {
                    $price = $value['form']['goods_price2'];
                    if (!empty($baojia_id) && !empty($value['form']['baojia'])) {
                        $baojia = $value['form']['baojia'];
                        if (isset($baojia[$baojia_id])) {
                            $price = bcadd($price, $baojia[$baojia_id],2);
                            if ($price <= 0) {
                                $price = 0.01;
                            }
                        }
                    }
                    if (!empty($shangjia_id) && !empty($value['form']['baojia_quyu'])) {
                        $baojia_quyu = $value['form']['baojia_quyu'];
                        if (isset($baojia_quyu[$shangjia_id])) {
                            $price = bcadd($price, $baojia_quyu[$shangjia_id],2);
                            if ($price <= 0) {
                                $price = 0.01;
                            }
                           
                        }
                    }

                    $specData['spec_list'][$key]['form']['goods_price2'] = $price;
               }else{
                    $price = $value['form']['goods_price'];
                    if (!empty($baojia_id) && !empty($value['form']['baojia'])) {
                        $baojia = $value['form']['baojia'];
                        if (isset($baojia[$baojia_id])) {
                            $price = bcadd($price, $baojia[$baojia_id],2);
                            if ($price <= 0) {
                                $price = 0.01;
                            }
                        }
                    }
                    if (!empty($shangjia_id) && !empty($value['form']['baojia_quyu'])) {
                        $baojia_quyu = $value['form']['baojia_quyu'];
                        if (isset($baojia_quyu[$shangjia_id])) {
                            $price = bcadd($price, $baojia_quyu[$shangjia_id],2);
                            if ($price <= 0) {
                                $price = 0.01;
                            }
                           
                        }
                    }

                    $specData['spec_list'][$key]['form']['goods_price'] = $price;
               }
            }
        }

        





        $this->success('', [

                                'detail'  => $detail,

                                'specData' => $specData

                          ]);

    }





     public function detailactivity()

    {

        $goods_id = $this->request->request('goods_id');

        $activity_id = $this->request->request('activity_id');

        // 商品详情

        $detail = Wxlitestoregoods::detail($goods_id);

        $imgs=[];

        foreach (explode(",",$detail['images']) as $index => $item) {

            $imgs[] = cdnurl($item, true);

        }

        $detail['imgs_url'] = $imgs;



        if (!$detail || $detail['goods_status'] !== '10') {

            $this->error('很抱歉，商品信息不存在或已下架');

        }

        // 规格信息

        $specData = $detail['spec_type'] === '20' ? $detail->getManySpecData($detail['spec_rel'], $detail['spec']) : null;



        // 这里对规格的img格式化

        // if($specData!=null){

        //     foreach($specData['spec_list'] as $index => $item){

        //         $specData['spec_list'][$index]["form"]['imgshow'] = $specData['spec_list'][$index]["form"]['spec_image']==='' ? null:cdnurl($specData['spec_list'][$index]["form"]['spec_image'], true);

        //     }

        // }



        $detail = $detail->toArray();

        foreach ($detail['spec'] as $key => $value) {

         

            $spec_sku_id = explode('_',$value['spec_sku_id']);

            $detail['spec'][$key]['goods_sku_id_arr'] = $spec_sku_id;

        }

        foreach ($detail['spec'] as $key => $value) {

            $detail['spec'][$key]['checked'] = false;

            $detail['spec'][$key]['goods_num'] = 0;

        }





        $map2['activity_id'] = $activity_id;

        $activity_goods = Db::table('fa_pifa_activity_sku_price')->where($map2)->column('*','goods_sku_price_id');



        



        if (!empty($activity_goods)) {





            foreach ($detail['spec'] as $key => $value) {





                  

                if (isset($activity_goods[$value['goods_spec_id']])) {

                    $detail['spec'][$key]['goods_price'] = $activity_goods[$value['goods_spec_id']]['price'];

                    $detail['spec'][$key]['stock_num'] = $activity_goods[$value['goods_spec_id']]['stock'];

                    $detail['spec'][$key]['sale'] = $activity_goods[$value['goods_spec_id']]['sales'];

                }

                    

            }

            

        }







        $this->success('', [

                                'detail'  => $detail,

                                'specData' => $specData

                          ]);

    }





    public function detail2()

    {

        $goods_id = $this->request->request('goods_id');

        // 商品详情

        $detail = Wxlitestoregoods::detail($goods_id);

        $imgs=[];

        foreach (explode(",",$detail['images']) as $index => $item) {

            $imgs[] = cdnurl($item, true);

        }

        $detail['imgs_url'] = $imgs;



        if (!$detail || $detail['goods_status'] !== '10') {

            $this->error('很抱歉，商品信息不存在或已下架');

        }

        // 规格信息

        $specData = $detail['spec_type'] === '20' ? $detail->getManySpecData($detail['spec_rel'], $detail['spec']) : null;



        // 这里对规格的img格式化

        // if($specData!=null){

        //     foreach($specData['spec_list'] as $index => $item){

        //         $specData['spec_list'][$index]["form"]['imgshow'] = $specData['spec_list'][$index]["form"]['spec_image']==='' ? null:cdnurl($specData['spec_list'][$index]["form"]['spec_image'], true);

        //     }

        // }



        $detail = $detail->toArray();

        foreach ($detail['spec'] as $key => $value) {

         

            $spec_sku_id = explode('_',$value['spec_sku_id']);

            $detail['spec'][$key]['goods_sku_id_arr'] = $spec_sku_id;

        }

        foreach ($detail['spec'] as $key => $value) {

            $detail['spec'][$key]['checked'] = false;

            $detail['spec'][$key]['goods_num'] = 0;

        }



        $map2['user_id'] = $this->auth->id;

        $map2['goods_id'] = $goods_id;

        $map2['status'] = '0';

        $info = Db::table('fa_pifa_userkan')->where($map2)->find();







        $this->success('', [

                                'detail'  => $detail,

                                'specData' => $specData,

                                'kan' => $info

                          ]);

    }



    public function category_list(){

        $categoryid = $this->request->request('id');

        $page = $this->request->request('page');

        $sortType = $this->request->request('types');

        $keyword = $this->request->request('keyword');

        $type = $this->request->request('type');

        $type1 = $this->request->request('type1');

        $type2 = $this->request->request('type2');

        $is_kan = $this->request->request('is_kan');

        $is_jifen = $this->request->request('is_jifen');

        $shangjia_id = $this->request->request('shangjia_id');

        $home_nav = $this->request->request('home_nav');





        $post = $this->request->request();



        // 筛选条件

        $filter = [];





      

        if (!empty($keyword)) {

            $filter['goods_name'] = ['like', '%' . trim($keyword) . '%'];

        }

        if (!empty($type)) {

            $categoryid = $type;

            

        }



        if (!empty($type1)) {

            $categoryid = $type1;

        }



        if (!empty($type2)) {

           

            $categoryid = $type2;

        }



       

        if (empty($is_jifen)) {

            $filter['is_jifen'] = 0;

        }else{

            $filter['is_jifen'] = $is_jifen;

        }



         if (empty($is_kan)) {

            $filter['is_kan'] = 0;

        }else{

            $filter['is_kan'] = $is_kan;

        }

        

        $filter['goods_status'] = '10';

        $filter['is_delete'] = '0';

        // if (!empty($shangjia_id)) {

        //     $filter['shangjia_id'] = $shangjia_id;

        // }



         // 排序规则

        $sort = 'goods_sort desc,createtime desc';

        // if ($sortType === 'normal') {

        //     $sort = ['goods_sort'=> 'desc', 'goods_id' => 'desc'];

        // } elseif ($sortType === 'sales') {

        //     $sort = ['goods_sales' => 'desc'];

        // } elseif ($sortType === 'price') {

        //     $sort = ['goods_min_price' => 'asc'];

        // }





        if (isset($post['home_nav'])) {

                

            $filter['home_nav'] = $post['home_nav'];

            



        }



        $tree = Tree::instance();

        $tree->init(collection(Db::table('fa_litestore_category')->select())->toArray(), 'pid');





        // if (isset($post['type1']) && isset($post['type2'])) {

        //     if (empty($post['type1']) && empty($post['type2'])) {

        //         $ids = $tree->getChildrenIds($post['type'],true);

        //         $filter['category_id'] = ['in',$ids];    

        //     }





        //     if (!empty($post['type1'])) {

                    



        //         if (empty($post['type2'])) {

        //             $ids = $tree->getChildrenIds($post['type1'],true);

        //             $filter['category_id'] = ['in',$ids];    

        //         }else{

        //             $filter['category_id'] = $post['type2'];    

        //         }





        //     }





        // }



        // 商品表名称

        $model_temp = new Wxlitestoregoods();

        $tableName = $model_temp->getTable();

        // 多规格商品 最高价与最低价

        $GoodsSpec = new Litestoregoodsspec();

        $minPriceSql = $GoodsSpec->field(['MIN(goods_price)'])

            ->where('goods_id', 'EXP', "= `$tableName`.`goods_id`")->buildSql();

        $maxPriceSql = $GoodsSpec->field(['MAX(goods_price)'])

            ->where('goods_id', 'EXP', "= `$tableName`.`goods_id`")->buildSql();

        



        if (empty($categoryid)) {

            $listdata = $model_temp->field(['*', '(sales_initial + sales_actual) as goods_sales',

            "$minPriceSql AS goods_min_price",

            "$maxPriceSql AS goods_max_price"

            ])->with(['spec'])->where($filter)->whereRaw("FIND_IN_SET('$shangjia_id', shangjia_id)")->order($sort)

            ->paginate(12, false, [ 'page' => $page ]);

        }else{

            $listdata = $model_temp->field(['*', '(sales_initial + sales_actual) as goods_sales',

            "$minPriceSql AS goods_min_price",

            "$maxPriceSql AS goods_max_price"

            ])->with(['spec'])->where($filter)->whereRaw("FIND_IN_SET('$shangjia_id', shangjia_id)")->whereRaw("FIND_IN_SET('$categoryid', category_id)")->order($sort)

            ->paginate(12, false, [ 'page' => $page ]);

        }

       



        $blistdatarList = [];



        $user_vip = [];



        if($this->auth->id){

      
            $map2['user_id'] = $this->auth->id;
            $map2['status'] = '1';
            $user_vip = Db::table('fa_pifa_md')->where($map2)->find();

        }



       

        



        foreach ($listdata as $index => $item) {

            $blistdatarList[] = ['image' => cdnurl(explode(",",$item['images'])[0], true), 'goods_name' => $item['goods_name'],

                                    'id'=> $item['goods_id'],'goods_min_price'=>$item['goods_min_price'],'goods_max_price'=>$item['goods_max_price'],'goods_sales'=>$item['goods_sales']];

            if (!empty($user_vip)) {
               $spec = $item['spec'];

               foreach ($spec as $key1 => $value1) {
                   $spec[$key1]['goods_price'] = $value1['goods_price2'];
               }
               $listdata[$index]['spec'] = $spec;

            }







        }

        $list = $listdata->toArray();
        $baojia_id = 0;
        if ($this->auth->id) {
           $user = Db::table('fa_user')->find($this->auth->id);
           if (!empty($user['baojia_id'])) {
               $baojia_id = $user['baojia_id'];
           }
        }



        foreach ($list['data'] as $index => $item) {

         

            if (!empty($user_vip)) {
              
                foreach ($item['spec'] as $key1 => $value1) {
                    $price = $value1['goods_price2'];
                    
                    if (!empty($baojia_id) && !empty($value1['baojia'])) {
                        $baojia = json_decode($value1['baojia'],true);
                        if (isset($baojia[$baojia_id])) {
                            $price = bcadd($price, $baojia[$baojia_id],2);
                            if ($price <= 0) {
                                $price = 0.01;
                            }
                        }
                    }
                    if (!empty($shangjia_id) && !empty($value1['baojia_quyu'])) {
                        $baojia_quyu = json_decode($value1['baojia_quyu'],true);
                        
                        if (isset($baojia_quyu[$shangjia_id])) {

                            $price = bcadd($price, $baojia_quyu[$shangjia_id],2);

                            if ($price <= 0) {
                                $price = 0.01;
                            }
                        }
                    }
                    $list['data'][$index]['spec'][$key1]['goods_price'] = $price;
                    $list['data'][$index]['spec'][$key1]['goods_price2'] = $price;

                }
                
                $list['data'][$index]['goods_min_price'] =  $list['data'][$index]['spec'][0]['goods_price2'];
            }else{


                foreach ($item['spec'] as $key1 => $value1) {
                    $price = $value1['goods_price'];
                    if (!empty($baojia_id) && !empty($value1['baojia'])) {

                        $baojia = json_decode($value1['baojia'],true);
                        if (isset($baojia[$baojia_id])) {
                           $price = bcadd($value1['goods_price'], $baojia[$baojia_id],2);
                            if ($price <= 0) {
                                $price = 0.01;
                            }
 
                        }
                    }
                    if (!empty($shangjia_id) && !empty($value1['baojia_quyu'])) {
                        $baojia_quyu = json_decode($value1['baojia_quyu'],true);

                        
                        if (isset($baojia_quyu[$shangjia_id])) {
                            $price = bcadd($price, $baojia_quyu[$shangjia_id],2);

                            if ($price <= 0) {
                                $price = 0.01;
                            }
                            $item['spec'][$key1]['goods_price'] = $price;
                        }
                    }
                    $list['data'][$index]['spec'][$key1]['goods_price'] = $price;
                    $list['data'][$index]['spec'][$key1]['goods_price2'] = $price;
                }
             
               $list['data'][$index]['goods_min_price'] =  $list['data'][$index]['spec'][0]['goods_price'];
            }

           
        }

        

     



         $this->success('', $list);



        

    }







    public function tuijian_list(){

        $categoryid = $this->request->request('id');

        $page = $this->request->request('page');

        $sortType = $this->request->request('types');

        $keyword = $this->request->request('keyword');

        $type = $this->request->request('type');

        $is_kan = $this->request->request('is_kan');

        $is_jifen = $this->request->request('is_jifen');

        $shangjia_id = $this->request->request('shangjia_id');



        // 筛选条件

        $filter = [];





        if (!empty($categoryid)) {

            $filter['category_id'] = $categoryid;

        }

        if (!empty($keyword)) {

            $filter['goods_name'] = ['like', '%' . trim($keyword) . '%'];

        }

        if (!empty($type)) {

            $filter['category_id'] = $type;

        }



        if (empty($is_jifen)) {

            $filter['is_jifen'] = 0;

        }else{

            $filter['is_jifen'] = $is_jifen;

        }



         if (empty($is_kan)) {

            $filter['is_kan'] = 0;

        }else{

            $filter['is_kan'] = $is_kan;

        }

        

        $filter['goods_status'] = '10';

        $filter['is_delete'] = '0';

        $filter['is_tuijian'] = 1;



        if (!empty($shangjia_id)) {

            $filter['shangjia_id'] = $shangjia_id;

        }







         // 排序规则

        $sort = [];

        if ($sortType === 'normal') {

            $sort = ['goods_sort'=> 'desc', 'goods_id' => 'desc'];

        } elseif ($sortType === 'sales') {

            $sort = ['goods_sales' => 'desc'];

        } elseif ($sortType === 'price') {

            $sort = ['goods_min_price' => 'asc'];

        }







        // 商品表名称

        $model_temp = new Wxlitestoregoods();

        $tableName = $model_temp->getTable();

        // 多规格商品 最高价与最低价

        $GoodsSpec = new Litestoregoodsspec();

        $minPriceSql = $GoodsSpec->field(['MIN(goods_price)'])

            ->where('goods_id', 'EXP', "= `$tableName`.`goods_id`")->buildSql();

        $maxPriceSql = $GoodsSpec->field(['MAX(goods_price)'])

            ->where('goods_id', 'EXP', "= `$tableName`.`goods_id`")->buildSql();

        

        $listdata = $model_temp->field(['*', '(sales_initial + sales_actual) as goods_sales',

            "$minPriceSql AS goods_min_price",

            "$maxPriceSql AS goods_max_price"

        ])->with(['spec'])->where($filter)->order($sort)->limit(10)

        ->select();



        $blistdatarList = [];

        foreach ($listdata as $index => $item) {

            $blistdatarList[] = ['image' => cdnurl(explode(",",$item['images'])[0], true), 'goods_name' => $item['goods_name'],

                                    'id'=> $item['goods_id'],'goods_min_price'=>$item['goods_min_price'],'goods_max_price'=>$item['goods_max_price'],'goods_sales'=>$item['goods_sales']];

        }



        $pagedata = $listdata;

        // $this->success('', [

        //                         'listdata'  => $blistdatarList,

        //                         'pagedata' => $pagedata,

        //                   ]);



           $this->success('', $pagedata);



        

    }





    public function category_list2(){

        $categoryid = $this->request->request('id');

        $page = $this->request->request('page');

        $sortType = $this->request->request('types');

        $keyword = $this->request->request('keyword');

        $type = $this->request->request('type');

        $is_kan = $this->request->request('is_kan');



        // 筛选条件

        $filter = [];





        if (!empty($categoryid)) {

            $filter['category_id'] = $categoryid;

        }

        if (!empty($keyword)) {

            $filter['goods_name'] = ['like', '%' . trim($keyword) . '%'];

        }

        if (!empty($type)) {

            $filter['category_id'] = $type;

        }



        if (empty($is_jifen)) {

            $filter['is_jifen'] = 0;

        }else{

            $filter['is_jifen'] = $is_jifen;

        }



         if (empty($is_kan)) {

            $filter['is_kan'] = 0;

        }else{

            $filter['is_kan'] = $is_kan;

        }

        

        $filter['goods_status'] = '10';

        $filter['is_delete'] = '0';



         // 排序规则

        $sort = [];

        if ($sortType === 'normal') {

            $sort = ['goods_sort'=> 'desc', 'goods_id' => 'desc'];

        } elseif ($sortType === 'sales') {

            $sort = ['goods_sales' => 'desc'];

        } elseif ($sortType === 'price') {

            $sort = ['goods_min_price' => 'asc'];

        }







        // 商品表名称

        $model_temp = new Wxlitestoregoods();

        $tableName = $model_temp->getTable();

        // 多规格商品 最高价与最低价

        $GoodsSpec = new Litestoregoodsspec();

        $minPriceSql = $GoodsSpec->field(['MIN(goods_price)'])

            ->where('goods_id', 'EXP', "= `$tableName`.`goods_id`")->buildSql();

        $maxPriceSql = $GoodsSpec->field(['MAX(goods_price)'])

            ->where('goods_id', 'EXP', "= `$tableName`.`goods_id`")->buildSql();

        

        $listdata = $model_temp->field(['*', '(sales_initial + sales_actual) as goods_sales',

            "$minPriceSql AS goods_min_price",

            "$maxPriceSql AS goods_max_price"

        ])->with(['spec'])->where($filter)->order($sort)

        ->paginate(8, false, [ 'page' => $page ]);



        $blistdatarList = [];

        foreach ($listdata as $index => $item) {

            $blistdatarList[] = ['image' => cdnurl(explode(",",$item['images'])[0], true), 'goods_name' => $item['goods_name'],

                                    'id'=> $item['goods_id'],'goods_min_price'=>$item['goods_min_price'],'goods_max_price'=>$item['goods_max_price'],'goods_sales'=>$item['goods_sales']];

        }



        $pagedata = $listdata;

        // $this->success('', [

        //                         'listdata'  => $blistdatarList,

        //                         'pagedata' => $pagedata,

        //                   ]);



           $this->success('', $pagedata);



        

    }

}